import { defineStore } from 'pinia'
import { store } from '@/stores'
import type { DictDataVO } from '@/api/system/dict/dict_data'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getDictDataSimpleList } from '@/api/system/dict/dict_data'

// 数据字典只需要session storage，且有时效性
const { wsCache } = useCache('sessionStorage')

export interface DictValueType {
  label: string
  value: any
  colorType?: string
  cssClass?: string
}

export interface DictTypeType {
  dictType: string
  dictValue: DictValueType[]
}

export interface DictState {
  dictMap: Map<String, any>
  isDictSet: boolean
}

/**
 * 存储 数据字典 的状态
 */
export const useDictStore = defineStore('dict', {
  state: (): DictState => {
    return {
      dictMap: new Map<String, any>(),
      isDictSet: false
    }
  },
  getters: {
    getDictMap(): Recordable {
      const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE)
      if (dictMap) {
        this.dictMap = dictMap
      }
      return this.dictMap
    },
    getIsDictSet(): boolean {
      return this.isDictSet
    }
  },
  actions: {
    async setDictMap() {
      const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE)
      if (dictMap) {
        this.dictMap = dictMap
        this.isDictSet = true
      } else {
        await this._fetchAndSetDict()
      }
    },
    getDictByType(type: string) {
      if (!this.isDictSet) {
        // 异步拉取
        this.setDictMap()
      }
      return this.dictMap[type]
    },
    async resetDict() {
      wsCache.delete(CACHE_KEY.DICT_CACHE)
      await this._fetchAndSetDict()
    },
    async _fetchAndSetDict() {
      const res = (await getDictDataSimpleList()) as DictDataVO[]
      const dictDataMap = new Map<string, any>()
      res.forEach((dictData: DictDataVO) => {
        const dictDataArray = dictDataMap[dictData.dictType!]
        if (!dictDataArray) {
          dictDataMap[dictData.dictType!] = []
        }
        // 处理 dictValue 层级
        dictDataMap[dictData.dictType!].push({
          value: dictData.value,
          label: dictData.label,
          colorType: dictData.colorType,
          cssClass: dictData.cssClass
        })
      })
      this.dictMap = dictDataMap
      this.isDictSet = true
      // 60秒内刷新页面则从缓存中重建state，超过60s重新从服务端获取最新数据
      wsCache.set(CACHE_KEY.DICT_CACHE, dictDataMap, { exp: 60 })
    }
  }
})

export const useDictStoreWithOut = () => {
  return useDictStore(store)
}
